export function loadMap() {
  if (window.BMap && window.BMap.Map) {
    return Promise.resolve()
  }

  let script = document.createElement('script')
  script.type = 'text/javascript'
  script.async = true
  script.src = `https://api.map.baidu.com/api?v=2.0&ak=${process.env.VUE_APP_BAIDU_AK}&callback=__initializeMap`

  let promise = new Promise((resolve, reject) => {
    window.__initializeMap = () => {
      return resolve()
    }

    script.onerror = (error) => {
      return reject(error)
    }
  })

  document.head.appendChild(script)

  return promise
}

export function getLocation(latLng) {
  if (!window.BMap || !window.BMap.Geocoder || !window.BMap.Point)
    throw new Error('百度地图未加载')
  return new Promise((res) => {
    let gc = new window.BMap.Geocoder()
    let point = new window.BMap.Point(latLng.longitude, latLng.latitude)
    gc.getLocation(point, (response) => {
      res(response)
    })
  })
}

export function getLatLng(address) {
  if (!window.BMap || !window.BMap.Geocoder) throw new Error('百度地图未加载')

  return new Promise((res) => {
    let gc = new window.BMap.Geocoder()
    gc.getPoint(address, (response) => {
      res(response)
    })
  })
}

export function getLocalSearch(location, options) {
  if (!window.BMap || !window.BMap.Geocoder) throw new Error('百度地图未加载')

  return new Promise((res) => {
    let local = new window.BMap.LocalSearch(location, options)
    res(local)
  })
}
